package org.dreamwork.seagragon;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import java.io.OutputStream;

/**
 * Created by IntelliJ IDEA.
 * User: seth
 * Date: 2010-4-24
 * Time: 22:24:37
 */
class WebPageWorker extends Thread {
    private String url;
    private OutputStream out;
    private ServletContext context;
    private String sessionId;

    WebPageWorker (ServletContext context, OutputStream out, String url, String sessionId) {
        this.url = url;
        this.out = out;
        this.context = context;
        this.sessionId = sessionId;
    }

    public String getSessionId () {
        return sessionId;
    }

    public void setSessionId (String sessionId) {
        this.sessionId = sessionId;
    }

    @Override
    public void run () {
        RequestDispatcher dispatcher = context.getRequestDispatcher (url);
        if (dispatcher == null) {
            context.log ("Serivce not avialbe: " + url);
            return;
        }

        try {
            ImitationServletOutputStream os = new ImitationServletOutputStream (out);
            ImitationHttpRequest    request = new ImitationHttpRequest (context, url, sessionId);
            ImitationHttpResponse  response = new ImitationHttpResponse (os);
            sessionId = request.getSession (true).getId ();
            dispatcher.include (request, response);
        } catch (Exception ex) {
            context.log (ex.getMessage (), ex);
        }
    }
}